layui.use(['treeSelector', 'form', 'tools'], function(){
    var $ = layui.jquery;
    var form = layui.form();
    var tools = layui.tools;
    var attributeId = tools.isEmpty(tools.GetQueryString('attribute_id'))?0:tools.GetQueryString('attribute_id');
    var categoryType = $('input[name="categroy_id"]').val();
    //var attributeIds = [];
    /*if(attributeId != 0){
        attributeIds[0] = attributeId;
    }*/
    layui.treeSelector({
        elem:'#category-tree',
        type:'radio',
        categoryType: 1,//普通分类
        focusId: [categoryType],
        callback: function(id){
            $.ajax({
                data: {category_ids:id},
                dataType: 'json',
                type: 'get',
                url: '/api/ProductAttribute/product_attribute_list/',
                error: function(){
                    layer.msg('接口错误');
                },
                success: function(json){
                    if(json.success){
                        var list = json.data;
                        var ids = list.ids;
                        if(list.length == 0){
                            $('.exist-attributes').addClass('layui-hide');
                            return false;
                        }
                        var str = '';
                        for(var i = 0; i < ids.length; i++){
                            str += '<a class="layui-btn layui-btn-mini" href="/productAttribute/edit?attribute_id='+ list[ids[i]].id +'">'+ list[ids[i]].attribute_name +'</a>';
                        }
                        $('.exist-attributes .site-block').html(str);
                        $('.exist-attributes').removeClass('layui-hide');
                    }
                }
            });
        }
    });

    form.on('select(attribute_type)', function(data){
        $('input[name="attribute_type"]').val(data.value);

        /*
            检索属性&规格属性 不能选择 文本表单类型
         */
        var formTypeInput = $('input[name="form_type"]');
        var formTypeSelect = formTypeInput.next('select');
        var selectStr = '';
        var selectType = 'select';
        switch(data.value){
            case '1'://普通属性 下拉 多选 单选 文本
                selectStr = '<option value="select">下拉</option>' +
                       '<option value="checkbox">多选</option>' +
                       '<option value="radio">单选</option>' +
                       '<option value="text">文本</option>';
                break;
            case '2'://检索属性 下拉 多选 单选
                selectStr = '<option value="select">下拉</option>' +
                    '<option value="checkbox">多选</option>' +
                    '<option value="radio">单选</option>';
                break;
            case '3'://规格属性 多选
                selectStr = '<option value="checkbox">多选</option>';
                selectType = 'checkbox';
                break;
        }
        formTypeSelect.find('option').remove();
        formTypeInput.val(selectType);
        $(selectStr).appendTo(formTypeSelect);
        form.render('select');
    });
    form.on('select(form_type)', function(data){
        $('input[name="form_type"]').val(data.value);
    });

    //获取属性值
    if(attributeId > 0) {
        var cid = $('input[name="categroy_id"]').val();
        getAttributeValue(attributeId, cid);
    }

    //添加属性值
    $('#add_attribute_value').on('click', function(){
        addAttributeTags();
    });
    $('input[name="attribute_value"]').on('keydown', function(e){
        if(e.keyCode == "13"){
            addAttributeTags();
        }
    });

    //删除属性值
    $(document).on('click', '.value_btns>.product-attributte-tag>i', function(e){
        e.stopPropagation();
        e.preventDefault();
        var newValue = $(this).parent('button').attr('data-new');
        if(newValue == '0'){
            $(this).parent('button').remove();
        }else{
            //删除已存在属性值
            var id = $(this).parent('button').attr('data-value');
            delAttributeValue(id);
        }
        if($('.value_btns').find('button.product-attributte-tag').length == 0){
            $('.value_btns').html('暂无记录');
        }
    });
    //双击编辑属性值
    $(document).on('dblclick', '.value_btns>.product-attributte-tag', function(e){
        e.stopPropagation();
        e.preventDefault();
        var btn = $(this);
        var vid = btn.attr('data-vid');
        var vname = btn.attr('data-vname');
        var vname2 = btn.children('span').text();
        var newInput = $('<input name="attr_'+ vid +'" class="new-input" value="'+ vname2 +'">');
        $(this).attr('data-update',vid);
        $(this).find('span').html(newInput);
        btn.attr('data-complete',0);
        newInput.select().on('keydown', function(e){
            if(e.keyCode == '13'){
                setAttributeValue(btn, newInput, vid, vname);
            }
        });
        newInput.on('blur', function(){
            setAttributeValue(btn, newInput, vid, vname);
        });
    });



    //保存
    $('#save').on('click', function(){
        var load = '';//loading
        var id = $('input[name="id"]').val();
        var attribute_name = $('input[name="attribute_name"]').val();
        if(attribute_name == ''){
            layer.msg('属性名不能为空');
            return false;
        }
        var categroy_id = $('input[name="categroy_id"]').val();
        if(categroy_id == '' || categroy_id == '0'){
            layer.msg('请选择分类');
            return false;
        }
        var attribute_type = $('input[name="attribute_type"]').val();
        var form_type = $('input[name="form_type"]').val();
        var attribute_value = {};
        var attribute_value2 = {};
        var f_order = $('input[name="f_order"]').val();
        $('.value_btns').find('.product-attributte-tag[data-new="0"]').each(function(i){
            attribute_value[i] = $(this).attr('data-value');
        });
        $('.value_btns').find('.product-attributte-tag[data-new="1"]').each(function(i){
            if($(this).attr('data-update') != '0' && $(this).attr('data-complete') == '1'){
                var updateVid = $(this).attr('data-update');
                attribute_value2[updateVid] = $(this).attr('data-value');
            }
        });
        var data = {
            id: id,
            f_order: f_order,
            form_type: form_type,
            category_id: categroy_id,
            attribute_name: attribute_name,
            attribute_type: attribute_type,
            attribute_value: attribute_value,
            attribute_value2: attribute_value2 //更新属性名
        };

        $.ajax({
            beforeSend: function(){
                load = layer.load(1, {
                    shade: [0.7,'#000']
                });
            },
            data: data,
            dataType: 'json',
            type: 'post',
            url: '/api/ProductAttribute/product_attribute_add/',
            error: function(){
                layer.close(load);
                layer.msg('接口错误');
            },
            success: function(json){
                layer.close(load);
                if(json.success){
                    layer.msg(json.errorMessage);
                    setTimeout(function(){
                        document.location.reload();
                    },1000);
                }else{
                    layer.msg(json.errorMessage);
                }
            }
        });
    });

    function addAttributeTags(){
        if($('.value_btns').find('button.product-attributte-tag').length == 0){
            $('.value_btns').empty();
        }
        var attribute_value = $('input[name="attribute_value"]').val();
        if(attribute_value == '') {
            layer.msg('属性值不能为空');
            return false;
        }
        $('<button type="button" class="layui-btn layui-btn-mini product-attributte-tag" data-value="'+ attribute_value +'" data-new="0" data-update="0" data-vid="0" data-vname="'+ attribute_value +'" data-complete="1"><span>'+attribute_value +'</span><i href="javascript:;" class="layui-icon">&#x1007;</i></button>').appendTo('.value_btns');
        $('input[name="attribute_value"]').val('').focus();
    }
    /**
     * 获取对应属性值
     * @param aid attribute_id
     * @param cid category_id
     */
    function getAttributeValue(aid, cid){
        var load = layer.load(1, {
            shade: [0.7,'#000']
        });
        if(tools.isEmpty(aid) || tools.isEmpty(cid)){
            document.location.href = '/productAttribute/add';
            return false;
        }
        $.ajax({
            data: {aid: aid, cid: cid},
            dataType: 'json',
            type: 'post',
            url: '/api/ProductAttribute/attribute_values',
            error: function(){
                layer.close(load);
                layer.msg('接口错误');
            },
            success: function(json){
                layer.close(load);
                if(json.success){
                    var list = json.data.list;
                    var listLen = json.data.total_num;
                    var str = '';
                    for(var i = 0; i < listLen; i++){
                        str += '<button type="button" class="layui-btn layui-btn-mini product-attributte-tag" data-value="'+ list[i].id +'" data-new="1" data-update="0" data-vid="'+ list[i].id +'" data-vname="'+ list[i].value_name +'" data-complete="1"><span>'+ list[i].value_name +'</span><i href="javascript:;" class="layui-icon">&#x1007;</i></button>';
                    }
                    $('.value_btns').html(str);
                }
            }
        });
    }

    /**
     * 删除属性名
     * @param id 属性值ID
     */
    function delAttributeValue(id){
        var load = layer.load(1, {
            shade: [0.7,'#000']
        });
        if(tools.isEmpty(id))
            return false;
        $.ajax({
            data: {id: id},
            dataType: 'json',
            type: 'post',
            url: '/api/ProductAttribute/del_attribute_value',
            error: function(){
                layer.close(load);
                layer.msg('接口错误');
            },
            success: function(json){
                layer.close(load);
                if(json.success){
                    var effectId = json.data.list[0];
                    $('.value_btns').find('button[data-value="'+ effectId +'"]').remove();
                }
                layer.msg(json.errorMessage);
            }
        });

    }

    /**
     * 更新属性名
     * @param btn
     * @param self
     * @param vid
     * @param vname
     */
    function setAttributeValue(btn, self, vid, vname){

        var newVname = $(self).val();
        if(vname == newVname){
            if(btn.attr('data-new') == '1'){
                btn.attr('data-update',0);
                btn.attr('data-value', vid);
            }
        }else{
            $(this).remove();
            btn.attr('data-value', newVname);
        }
        btn.children('span').text(newVname);
        btn.attr('data-complete',1);
    }
});